package cn.com.lookang;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * 条件注入
 * 参照springBoot的@ConditionalOnClass实现的
 *
 * @author: liulekang
 * @Date: 2019/6/3
 */
public class LogAutoAssemCondition implements Condition {
    private static final String className = "org.slf4j.Logger";

    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        ClassLoader classLoader = conditionContext.getClassLoader();
        if (null == classLoader) {
            classLoader = getDefaultClassLoader();
        }
        try {
            //加载不到类就会出ClassNotFoundException，认为没有logger这个类
            forName(className, classLoader);
            return true;
        } catch (Throwable tw) {
            return false;
        }
    }


    /**
     * @param className
     * @param classLoader
     * @return
     * @throws ClassNotFoundException
     */
    private static Class<?> forName(String className, ClassLoader classLoader) throws ClassNotFoundException {
        return classLoader != null ? classLoader.loadClass(className) : Class.forName(className);
    }

    /**
     * 获取类加载器
     *
     * @return
     */
    public static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;

        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable var3) {
        }

        if (cl == null) {
            cl = LogAutoAssemCondition.class.getClassLoader();
            if (cl == null) {
                try {
                    cl = ClassLoader.getSystemClassLoader();
                } catch (Throwable var2) {
                }
            }
        }
        return cl;
    }
}
